/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.pclong.util;

import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 *
 * @author Administrator
 */
public class ClassLoaderUtils {

    private static final Log log = LogFactory.getLog(ClassLoaderUtils.class);

    private ClassLoaderUtils() {
    }

    public static void addURL(String url, ClassLoader classLoader) {
        log.debug("addURL(),url->" + url);

        if (url.isEmpty()) {
            return;
        }
        ClassLoader threadContextClassLoader = classLoader;
        if (threadContextClassLoader == null) {
            threadContextClassLoader = Thread.currentThread().getContextClassLoader();
        }
        boolean is = threadContextClassLoader instanceof URLClassLoader;
        if (is) {
            try {
                URL realUrl = new URL(url);
                URLClassLoader curr = (URLClassLoader) threadContextClassLoader;
                Method add = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
                add.setAccessible(true);
                add.invoke(curr, new Object[]{realUrl});
            } catch (Exception e) {
                log.warn("WARN", e);
                throw new IllegalArgumentException(e);
            }
        } else {
            log.warn("the classloader is not a URLClassLoader type!");
            throw new IllegalArgumentException("the classloader is not a URLClassLoader type!");
        }
    }

    public static ClassLoader getDefaultClassLoader() {
        ClassLoader cl = null;
        try {
            cl = Thread.currentThread().getContextClassLoader();
        } catch (Throwable e) {
            log.info("INFO", e);
        }
        if (cl == null) {
            cl = ClassLoaderUtils.class.getClassLoader();
        }
        return cl;
    }
}
